﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EntityFramework.Extensions;

namespace DAO
{
    public class MessageDAO
    {
        private WebChatDBEntities db = new WebChatDBEntities();

        public IEnumerable<Message> GetMessages(int userId)
        {
            var messages = db.Messages.Where(m => m.ToUserId == userId && m.Seen == false).ToList();

            messages.ForEach(m => m.Seen = true);
            db.SaveChanges();

            return messages;
        }

        public IEnumerable<Message> GetMessages(int[] roomIds)
        {
            var messages = new List<Message>();

            foreach (int roomId in roomIds)
            {
                int id = roomId;
                var mes = db.Messages.Where(m => m.RoomId == id).AsEnumerable().Reverse().Take(20).AsEnumerable().Reverse().ToList();
                messages.AddRange(mes);
            }

            //messages.ForEach(m => m.Seen = true);
            //db.SaveChanges();
            return messages;
        }

        public void AddMessage(Message message)
        {
            message.Seen = false;
            db.Messages.Add(message);
            db.SaveChanges();
        }

        public void DeleteAllMessagesOfOneRoom(int roomId)
        {
            db.Messages.Delete(m => m.RoomId == roomId);
            db.SaveChanges();
        }
    }
}
